local apconfig = {}

tCount=0
tBreak=0
tStatus=0
apIndex=1
apMax=2

local apTable={{"HiWiFi_SMT","87654321","192.168.199.200"},{"NETGEAR71","shinyphoenix155","192.168.1.100"}}

function apconfig.apl()
	for i=1,#apTable do
		print("SSID:"..apTable[i][1]..","..apTable[i][2])
	end
end

function apconfig.startServer()
	print("xconsole Server running at: 8080,Heap: "..node.heap())
end

function apconfig.checkAP()
	if tBreak==1 then tmr.stop() end
	if wifi.sta.getip()=="0.0.0.0" or wifi.sta.getip()==nil then
		if (tStatus==1) then 
			tStatus=0
			net.server.close()
			tmr.alarm(3,2000, 1, apconfig.checkAP)
		end
		print(string.format("%d:Connect AP, Waiting...",tCount)) 
		tCount=tCount+1
		if tCount>5 then
			print("Trying SSID:"..apTable[apIndex][1]..","..apTable[apIndex][2])
			wifi.setmode(wifi.STATIONAP)
			wifi.sta.config(apTable[apIndex][1],apTable[apIndex][2])
			wifi.sta.connect()
			tCount=0
			apIndex = apIndex+1
			if apIndex>apMax then
				apIndex=1
			end
		end
	else
		if tStatus==0 then
			apconfig.startServer()
			tmr.alarm(3,20000, 1, apconfig.checkAP)
			tStatus = 1
		else
			print("*Tic: ["..tmr.now().."] Wifi AP OK. Server IP:"..wifi.sta.getip())
		end
	end
end

function apconfig.startconfig()
	tmr.alarm(3,2000, 1, apconfig.checkAP)
end

return apconfig
